package cn.edu.csust.coursecard.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zsw
 * @date 2021/4/22 14:38
 */
@Configuration
@EnableAsync
public class ExecutorConfig {
    
    @Bean("jwRequestExecutor")
    public ThreadPoolTaskExecutor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(5);
        // 配置最大线程数
        executor.setMaxPoolSize(5);
        // 配置队列大小
        executor.setQueueCapacity(9999);
        // 配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("Jw-Request-");

        // 配置拒绝策略,由调用者线程进行处理
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        executor.initialize();
        return executor;
    }
    
//    public ExecutorService jwRequestExecutor(){
//
//        return new ThreadPoolExecutor(
//                5,  //核心线程数
//                5,  //最大线程数
//                0, //救急线程存活时间
//                TimeUnit.MILLISECONDS,  //时间单位
//                new LinkedBlockingQueue<>(9999), //阻塞队列
//                new ThreadFactory() {
//                    final AtomicInteger i = new AtomicInteger(0);
//                    @Override
//                    public Thread newThread(@NotNull Runnable r) {
//                        return new Thread(r,"Jw-Request-" + i);
//                    }
//                }, //线程命名
//                new ThreadPoolExecutor.CallerRunsPolicy() //拒绝策略
//        );
//    }
}
